function [Dpi,Dp,p_ij] = Dprofits_Dq(q_ij,beta,delta,s_i,cobb_par,E,M,r,K_obs,c_inv,W_k,U_k,J_k,sigma,sf)

% Here we compute the derivative of the platform's profits with respect to q_ij
% See Appendix C.4 for a derivation.

%--------------- Compute prices p_ij that ensure that exactly q_ij exporters 
%                demand transportation on route ij
p_ij = prices(q_ij,beta,delta,s_i,cobb_par,E,M,r,K_obs,c_inv,sf);

% number of entrants that sustains allocation (q_ij,s_i) 

etilde_ij = entrants(q_ij,s_i,cobb_par,M,delta,sf);
e_i = inverse_m(nansum(q_ij,2),s_i,cobb_par,M,sf);
q_i = nansum(q_ij,2);
lambdae_i = q_i./e_i;

%--------------- derivatives etilde_ij

De = zeros(M,M,M);
for i = 1:M
    for j = 1:M
        
        De(i,j,j) = 1;
        
    end
end

%--------------- derivatives entry probabilities

DG = zeros(M,M);
for i = 1:M
    for j = 1:M
        for k = 1:M
            DG(i,j,k) = 1./(E(i) - nansum(etilde_ij(i,:)));
            if j ==k
                DG(i,j,k) = DG(i,j,k) + 1./q_ij(i,j);
            end
        end
    end
end
%--------------- derivatives prices
Dp = zeros(M,M,M);


for i = 1:M
    for j = 1:M
        for k = 1:M
            Dp(i,j,k) = -DG(i,j,k);
        end
    end
end

%--------------- derivative profits

Dpi = zeros(M,M);
for i = 1:M
    for j= 1:M
        if i~=j
            Dpi(i,j) = p_ij(i,j) + nansum(q_ij(i,:).*Dp(i,:,j)) + (W_k(i,j) - J_k(i))./sigma;
        end
    end
end

end

